
from werkzeug.routing import BaseConverter
from functools import wraps
from flask import current_app, jsonify, session,g


from ihome.utils.response_code import RET,error_map
from ihome import constants,db

# 自定义转换器
class Reconverter(BaseConverter):
    def __init__(self, url_map,regex):
        super(Reconverter, self).__init__(url_map)
        self.regex = regex

def data_base_error(view_func):
    @wraps(view_func)
    def wrapper(*args,**kwargs):
        try:
            result = view_func(*args,**kwargs)
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()  # 优化的话 就是捕捉数据库的错误 对那次数据库错误进行rollback()
            return jsonify(constants.return_template_json(RET.DATAERR,error_map.get(RET.DATAERR)))
        return result
    return wrapper

def login_status(view_func):
    @wraps(view_func)
    def wrapper(*args,**kwargs):
        # 判断用户登陆状态
        # 如果用户是登陆的，执行视图函数 状态放在g中
        # 未登陆返回首页
        user_id = session.get('user_id')
        if user_id is not None:
            try:
                from ihome.models import User
                user = User.query.get(user_id)
                g.user = user
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(constants.return_template_json(RET.DATAERR,error_map.get(RET.DATAERR)))
            return view_func(*args, **kwargs)
        else:
            return jsonify(constants.return_template_json(RET.SESSIONERR, error_map.get(RET.SESSIONERR)))
    return wrapper
